package com.ak.httpclient;

import com.ak.utils.HttpUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Random;


/**
 * 请求内容
 * 爬取豆瓣的内容，因为豆瓣使用了爬虫所以需要一些工具类
 */
public class MyHttpGetParams {

    public static void main(String[] args) {
        // 打开浏览器
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(HttpUtils.cm).build();
        CloseableHttpResponse response=null;
        // 设置参数
        // 分析这个
        // https://movie.douban.com/tag/#/?sort=U&range=0,10&tags=%E5%8A%A8%E4%BD%9C,%E7%94%B5%E5%BD%B1
        try {
            // https://movie.douban.com/tag/
            URIBuilder uriBuilder = new URIBuilder("https://movie.douban.com/tag/");
            uriBuilder.setParameter("sort","U");
            uriBuilder.setParameter("range","0,10");
            uriBuilder.setParameter("tags","电影");
            // 输入网址
            HttpGet httpGet=new HttpGet(uriBuilder.build());
            httpGet.setConfig(HttpUtils.getConfig());
            int agentNum = new Random().nextInt(HttpUtils.agents.size());
            httpGet.addHeader("User-Agent", HttpUtils.agents.get(agentNum));

            // 获取响应内容
           response= httpClient.execute(httpGet);
            
            if(response.getStatusLine().getStatusCode()==200){
                String content = EntityUtils.toString(response.getEntity());
                System.out.println(content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 关闭流
            if(response!=null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
